package com.example.project13;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.Settings;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class GpsActivity extends AppCompatActivity implements GpsBindService.GpsCallback {
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
    private static final int BACKGROUND_LOCATION_PERMISSION_REQUEST_CODE = 2;
    private GpsBindService gpsService;
    private boolean isBound = false;
    private TextView tvLocation;
    private Handler mainHandler;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            GpsBindService.LocalBinder binder = (GpsBindService.LocalBinder) service;
            gpsService = binder.getService();
            isBound = true;
            
            // 注册GPS回调
            binder.setGpsCallback(GpsActivity.this);
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            isBound = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gps);
        
        tvLocation = findViewById(R.id.tv_location);
        mainHandler = new Handler();
        
        // 检查位置权限
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            // 请求位置权限
            ActivityCompat.requestPermissions(this,
                    new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                    LOCATION_PERMISSION_REQUEST_CODE);
        } else {
            // 检查后台位置权限（Android 10及以上）
            checkBackgroundLocationPermission();
        }
    }

    private void checkBackgroundLocationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_BACKGROUND_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                // 请求后台位置权限
                ActivityCompat.requestPermissions(this,
                        new String[]{android.Manifest.permission.ACCESS_BACKGROUND_LOCATION},
                        BACKGROUND_LOCATION_PERMISSION_REQUEST_CODE);
            } else {
                // 已有所有权限，绑定GPS服务
                bindGpsService();
            }
        } else {
            // Android 10以下版本不需要后台位置权限
            bindGpsService();
        }
    }

    private void bindGpsService() {
        // 绑定GPS服务
        Intent intent = new Intent(this, GpsBindService.class);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 基本位置权限被授予，检查后台位置权限
                checkBackgroundLocationPermission();
            } else {
                // 基本位置权限被拒绝
                Toast.makeText(this, "需要位置权限才能获取GPS信息", Toast.LENGTH_LONG).show();
                finish();
            }
        } else if (requestCode == BACKGROUND_LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 后台位置权限被授予，绑定GPS服务
                bindGpsService();
            } else {
                // 后台位置权限被拒绝
                Toast.makeText(this, "需要后台位置权限以在后台获取GPS信息", Toast.LENGTH_LONG).show();
                // 引导用户到设置页面手动授权
                openAppSettings();
            }
        }
    }

    private void openAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivity(intent);
    }

    @Override
    public void onGpsUpdate(double latitude, double longitude) {
        // 在主线程更新UI
        mainHandler.post(() -> {
            String locationText = String.format("当前位置：纬度 %.4f°，经度 %.4f°", latitude, longitude);
            tvLocation.setText(locationText);
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isBound) {
            unbindService(serviceConnection);
            isBound = false;
        }
    }
}